<template>
  <el-dialog v-if="load" :title="title" v-model="visible" align-center width="700" :close-on-click-modal="false" @close="handleClose" class="dialog">
    <div class="warning-text">
      <div class="dk-iconfont icon-Warning"></div>
      建议填写账号注册地址，避免不同账号发货地址相同引起关联！
    </div>
    <el-form label-width="120px" :model="formData" inline :rules="rules" ref="ruleFormRef" label-position="top" class="form mt-[6px]">
      <el-form-item label="店铺名称" style="width: 400px">
        <SelectShop class="shopName w-[260px]" v-model="formData.source_shop_id" @change="changeShop"></SelectShop>
        <el-button type="primary" @click="syncAddress">同步发票地址</el-button>
      </el-form-item>
      <el-form-item label="姓名" prop="name" class="w-[30%]">
        <el-input v-model="formData.name" placeholder="姓名" />
      </el-form-item>
      <el-form-item label="国家" prop="country_id" class="w-[40%]">
        <SelectCountry class="w-full" v-model="formData.country_id" valueKey="id" placeholder="请选择国家" @changeLabel="(val) => (formData.country = val)"></SelectCountry>
      </el-form-item>
      <el-form-item label="邮政编码" class="w-[30%]">
        <el-input v-model="formData.zip_code" placeholder="邮政编码" />
      </el-form-item>

      <el-form-item label="州/省" class="w-[100%] mb0">
        <el-form-item class="mr-[0]">
          <el-input v-model="formData.province" placeholder="州/省" />
        </el-form-item>
        <el-form-item prop="city" class="mr-[0]">
          <el-input v-model="formData.city" placeholder="市" />
        </el-form-item>
        <el-form-item class="mr-[0]">
          <el-input v-model="formData.district" placeholder="区/县" />
        </el-form-item>
      </el-form-item>

      <el-form-item label="街道地址1" prop="preferred_address" class="w-[100%]">
        <el-input v-model="formData.preferred_address" placeholder="街道地址1" />
      </el-form-item>
      <el-form-item label="街道地址2" class="w-[100%]">
        <el-input v-model="formData.alternate_address" placeholder="街道地址2" />
      </el-form-item>

      <el-form-item label="公司名称" class="w-[100%]">
        <el-input v-model="formData.company_name" placeholder="公司名称" />
      </el-form-item>

      <el-form-item label="电话" prop="telephone">
        <el-input v-model="formData.telephone" placeholder="电话" />
      </el-form-item>
      <el-form-item label="手机号码" prop="mobile_number">
        <el-input v-model="formData.mobile_number" placeholder="手机号码" />
      </el-form-item>
      <el-form-item label="传真">
        <el-input v-model="formData.fax" placeholder="传真" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" placeholder="邮箱" />
      </el-form-item>
      <el-form-item label="网址">
        <el-input v-model="formData.web_site" placeholder="网址" />
      </el-form-item>
      <el-form-item label="银行信息" class="w-[100%]">
        <el-input v-model="formData.bank_info" placeholder="银行信息" />
      </el-form-item>
      <el-form-item label="运输类型" style="width: 340px" class="mr-[0]">
        <el-select v-model="formData.shipping_type" placeholder="请选择运输类型" class="w-[320px]" @change="changeShipping">
          <el-option v-for="item in transportationType" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否默认地址" class="w-[160px]">
        <el-select v-model="formData.is_default_address" placeholder="请选择" class="w-[120px]">
          <el-option v-for="item in isDefaultOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings.submit" @click="submit">保 存</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { reactive, toRefs } from "vue"
import { batchUpdate, getShopShippingAddress } from "../api"
import SelectShop from "@/components/Selects/SelectShop"
import SelectCountry from "@/components/Selects/SelectCountry"
import { ElMessage } from "element-plus"
const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
const ruleFormRef = ref()

const transportationType = [
  { label: "快递", value: 10 },
  { label: "空运", value: 11 },
  { label: "快海运", value: 12 },
  { label: "慢海运(海卡)", value: 13 },
  { label: "铁运", value: 14 },
  { label: "卡航", value: 15 },
  { label: "邮政小包", value: 16 },
  { label: "专线小包", value: 17 },
  { label: "其他", value: 18 },
]

const isDefaultOptions = [
  { label: "是", value: 1 },
  { label: "否", value: 0 },
]

const data = reactive({
  formData: {},
  ids: [],
  title: "",
  handleType: "",
})

const { formData, ids, title, handleType } = toRefs(data)
// const emit = defineEmits(['close', 'add', 'edit', 'query'])
const emit = defineEmits(["add", "edit", "query"])
//座机验证
const checktelephone = (rule, value, callback) => {
  if (!value) {
    callback()
  } else {
    const reg = /^0\d{2,3}[-]?\d{7,8}|0\d{2,3}\s?\d{7,8}$/
    if (reg.test(value)) {
      callback()
    } else {
      return callback(new Error("请输入正确的电话"))
    }
  }
}
//手机号验证
const checkPhone = (rule, value, callback) => {
  if (!value) {
    callback()
  } else {
    const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
    const phoneReg = /^\d{3}-\d{8}|\d{4}-\d{7}$/
    if (reg.test(value) || phoneReg.test(value)) {
      callback()
    } else {
      return callback(new Error("请输入正确的联系电话"))
    }
  }
}
const checkEmail = (rule, value, callback) => {
  const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
  if (!value) {
    callback()
  }
  setTimeout(() => {
    if (mailReg.test(value)) {
      callback()
    } else {
      callback(new Error("请输入正确的邮箱格式"))
    }
  }, 100)
}

const rules = reactive({
  country_id: [{ required: true, message: "请选择", trigger: "change" }],
  name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  preferred_address: [{ required: true, message: "不能为空", trigger: "blur" }],
  city: [{ required: true, message: "不能为空", trigger: "blur" }],
})

const statusMap = new Map([
  ["add", "添加发货地址"],
  ["edit", "编辑发货地址"],
  ["batch", "批量上传店铺发货地址"],
])

// 打开弹窗
const open = async (type, arr, obj = {}) => {
  title.value = statusMap.get(type)
  handleType.value = type
  if (!load.value) {
    load.value = true
    await 1
  }
  ids.value = arr
  formData.value = obj
  loadings = reactive({})
  visible.value = true
}
// 关闭弹窗
const close = () => {
  visible.value = false
  formData.value = {}
  ids.value = []
  ruleFormRef.value.resetFields()
}

const handleClose = () => {
  visible.value = false
}
const callbackHandleClose = () => {
  visible.value = false
  emit("query")
}
const submit = async () => {
  let { validate } = ruleFormRef.value
  validate((valid) => {
    if (valid) {
      if (handleType.value == "batch") {
        loadings.submit = true
        batchUpdate({ ids: ids.value, shopAddress: formData.value })
          .then((res) => {
            ElMessage({ message: "保存成功！", type: "success" })
            close()
          })
          .finally(() => {
            loadings.submit = false
          })
      } else if (handleType.value == "add") {
        emit("add", formData.value, callbackHandleClose)
      } else if (handleType.value == "edit") {
        emit("edit", formData.value, callbackHandleClose)
      }
    }
  })
}

const changeShop = (val) => {
  formData.value.source_shop = val
}

const syncAddress = async () => {
  if (!formData.value.source_shop_id) {
    ElMessage.error("请选择店铺")
    return
  }
  try {
    const res = await getShopShippingAddress({
      shop_id: formData.value.source_shop_id,
      address_type: 1,
    })
    if (!res.data.length) {
      ElMessage.error("店铺发票地址为空，请检查再进行同步操作")
      return
    }
    formData.value = {
      ...res.data?.[0],
      source_shop_id: formData.value.source_shop_id,
      source_shop: formData.value.source_shop,
    }
  } catch (e) {
    throw Error(e)
  }
}

const changeShipping = (val) => {
  const item = transportationType.find((i) => i.value == val)
  formData.value.shipping_name = item?.label
}

defineExpose({ open })
</script>
<style lang="scss" scoped>
.el-form {
  .el-form-item {
    width: 31%;
    margin-right: 12px;
  }
}
.warning-text {
  display: flex;
  justify-items: center;
  align-items: center;
  padding: 8px;
  background: #fafafa;
  font-size: 12px;
  color: #333;
  .el-icon {
    font-size: 14px;
  }
}
</style>
